# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import logging
import typing as t
from abc import ABC, abstractmethod

from ksai.document.context import DocumentException, DocumentSection
from ksai.persistence.storage.attachment import Attachment

logger = logging.getLogger(__name__)


class DocumentExtractorException(DocumentException):
    pass


class DocumentExtractor(ABC):

    def __init__(self):
        super().__init__()

    @abstractmethod
    def extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        raise NotImplementedError

    @abstractmethod
    def supports(self, attachment: Attachment) -> bool:
        raise NotImplementedError

    @abstractmethod
    def extensions(self) -> t.List[str]:
        return []

    @abstractmethod
    def mimes(self) -> t.List[str]:
        return []

    @abstractmethod
    def is_cacheable(self) -> bool:
        raise NotImplementedError


class AbstractDocumentExtractor(DocumentExtractor, ABC):
    def __init__(self):
        super().__init__()

    def extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        if self.supports(attachment):
            return self.do_extract(attachment)
        return []

    @abstractmethod
    def do_extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        raise NotImplementedError

    def is_cacheable(self) -> bool:
        return True

    def supports(self, attachment: Attachment) -> bool:
        extensions = self.extensions()
        if len(extensions) > 0 and attachment.suffix.lower() in extensions:
            return True

        mimes = self.mimes()
        if len(mimes) > 0 and attachment.mime in mimes:
            return True
        return False
